package com.sjjy.ta.impl;

import com.sjjy.dao.model.*;
import com.sjjy.ta.iface.MonitoringService;
import com.sys.plat.service.base.BaseServiceImpl;
import com.sys.tool.FileTool;
import com.sys.tool.HttpClientTool;
import com.sys.tool.StringTool;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.apache.struts.taglib.html.ImgTag;
import org.hibernate.Transaction;
import org.hibernate.classic.Session;
import org.htmlparser.Node;
import org.htmlparser.NodeFilter;
import org.htmlparser.Parser;
import org.htmlparser.filters.AndFilter;
import org.htmlparser.filters.HasAttributeFilter;
import org.htmlparser.filters.TagNameFilter;
import org.htmlparser.tags.ImageTag;
import org.htmlparser.tags.LinkTag;
import org.htmlparser.util.NodeList;
import org.htmlparser.util.ParserException;
import org.htmlparser.visitors.HtmlPage;

import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by IntelliJ IDEA.
 * User: mabo
 * Date: 2011-3-7
 * Time: 13:53:38
 * To change this template use File | Settings | File Templates.
 */
public class MonitoringImpl extends BaseServiceImpl implements MonitoringService {
    HttpClientTool hct = new HttpClientTool();

    public MonitoringImpl() {
    }

    public String login() {
        hct.setUrl("http://www.jiayuan.com/login/dologin.php?pre_url=/usercp&name=mabo%40ccapp.net&password=111222&remem_pass=on&ljg_login=1");
        hct.getInnerHTML();
        hct.setUrl("http://search.jiayuan.com/result.php?save_id=175998");
        return hct.getInnerHTML();
    }


    public List<Map<String, String>> getOlMMlist() {

        hct.setUrl("http://www.jiayuan.com/usercp/clicked.php");

        List<Map<String, String>> list = new ArrayList<Map<String, String>>();

        Map<String, String> map = new HashMap();
        map.put("id", "");
        map.put("url", "");
        map.put("name", "");
        map.put("imp", "");
        map.put("mail", "");
        map.put("other", "");


        Parser parser = Parser.createParser(hct.getInnerHTML(), "utf-8");
        HtmlPage page = new HtmlPage(parser);

        try {
            parser.visitAllNodesWith(page);
        } catch (ParserException e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        }


        NodeList nodelist = page.getBody();
        NodeFilter filter = new HasAttributeFilter("class", "match_photobox");
        nodelist = nodelist.extractAllNodesThatMatch(filter, true);

        Node[] ns = nodelist.toNodeArray();

        for (Node n : ns) {
            map = new HashMap();

            NodeFilter nfilter = new TagNameFilter("img");
            nodelist = n.getChildren().extractAllNodesThatMatch(nfilter, true);
            if (nodelist.toNodeArray()[0] instanceof ImageTag) {
                ImageTag img = (ImageTag) nodelist.toNodeArray()[0];
                map.put("img", img.getImageURL());
            }

            nfilter = new TagNameFilter("a");
            Node[] nn = n.getChildren().extractAllNodesThatMatch(nfilter, true).toNodeArray();
            if (nn[1] instanceof LinkTag) {
                LinkTag l = (LinkTag) nn[1];
                map.put("id", l.getLink().replace("http://www.jiayuan.com/", ""));
                map.put("url", l.getLink());
                map.put("name", l.getLinkText());
            }

            if (nn[2] instanceof LinkTag) {
                LinkTag l = (LinkTag) nn[2];
                map.put("other", l.getLinkText().replace("show_title(\"", "").replace("\")", ""));
            }

            if (nn[3] instanceof LinkTag) {
                LinkTag l = (LinkTag) nn[3];
                map.put("mail", l.getLink());
            }
            list.add(map);
        }

        return list;
    }


    public void saveUserData(List<Map<String, String>> list) {
        for (Map<String, String> map : list) {
            /*System.out.println(map.get("id"));
            System.out.println(map.get("name"));
            System.out.println(map.get("url"));
            System.out.println("========");*/


            List ul = dao.listByHql("FROM UserInfo WHERE u_id = ?", map.get("id").toString());
            if (ul.size() > 0) {
                UserInfo ui = (UserInfo) ul.get(0);
                if (ui.getType().equals("2") && ui.getuDate() == null) {
                    ui.setuDate(new Date());
                    ui.setType("3");
                    dao.updateObject(ui);
                }
            } else {
                UserInfo ui = new UserInfo();
                ui.setuId(map.get("id"));
                ui.setName(map.get("name"));
                ui.setImg(map.get("img"));
                ui.setUrl(map.get("url"));
                ui.setMail(map.get("mail"));
                ui.setOther(map.get("other"));
                ui.setType("1");
                ui.setuDate(new Date());
                ui.setCreateDate(new Date());
                dao.saveObject(ui);
            }
        }
    }

    public void startMonitorOnline() {
        this.login();
        try {
            this.saveInMail();
            this.saveOutMail();
            this.saveUserData(this.getOlMMlist());
            this.saveNewUserList();
        } catch (Exception e) {
            FileTool ft = new FileTool("D:\\sjjyLOG");
            ft.createFile(new Date().toString().replace(" ", "_").replace(":", "_"), e.toString());
        }
    }


    private Set getOutMailID() {
        Set set = new HashSet();
        hct.setUrl("http://www.jiayuan.com/msg/outbox.php?&p=1#toppage");
        hct.getInnerHTML();

        Parser p = Parser.createParser(hct.getInnerHTML(), "UTF-8");
        HtmlPage page = new HtmlPage(p);
        try {
            p.visitAllNodesWith(page);
        } catch (ParserException e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        }

        NodeList nodelist = page.getBody();

        NodeFilter nf = new HasAttributeFilter("class", "nm ");
        nodelist = nodelist.extractAllNodesThatMatch(nf, true);


        Node[] n = nodelist.toNodeArray();
        for (Node node : n) {
            nodelist = node.getChildren().extractAllNodesThatMatch(new TagNameFilter("a"), true);
            LinkTag l = (LinkTag) nodelist.toNodeArray()[0];
            set.add(l.getLink());
        }
        return set;
    }


    public void saveOutMail() {

        Set<String> set = this.getOutMailID();

        for (String url : set) {
            OutMail om = new OutMail();
            hct.setUrl(url);

            om.setMailId(url.substring(url.indexOf("=") + 1, url.length() - 18));

            Parser p = Parser.createParser(hct.getInnerHTML(), "UTF-8");
            HtmlPage page = new HtmlPage(p);
            try {
                p.visitAllNodesWith(page);
            } catch (ParserException e) {
                e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
            }

            NodeList nodeBodylist = page.getBody();
            NodeList nodelist;
            Node[] n;


            nodelist = nodeBodylist.extractAllNodesThatMatch(new HasAttributeFilter("class", "recipient_status"), true);

            n = nodelist.toNodeArray();
            for (Node node : n) {
                nodelist = node.getChildren().extractAllNodesThatMatch(new TagNameFilter("a"), true);
                if (nodelist.size() > 0) {
                    LinkTag l = (LinkTag) nodelist.toNodeArray()[0];
                    System.out.println(l.getLink().replace("http://www.jiayuan.com/", "").replace("?lt=msgbox", ""));
                    om.setUserId(l.getLink().replace("http://www.jiayuan.com/", "").replace("?lt=msgbox", ""));
                }
            }

            if (om.getUserId() == null || om.getUserId().equals("")) {
                continue;
            }


            nodelist = nodeBodylist.extractAllNodesThatMatch(new AndFilter(new TagNameFilter("li"), new HasAttributeFilter("class", "time")), true);
            n = nodelist.toNodeArray();

            String date = "";
            if (nodelist.size() > 0) {
                n = nodelist.toNodeArray();
                System.out.println(n[0].toPlainTextString().replace("发信时间：", ""));

                date = n[0].toPlainTextString().replace("发信时间：", "");
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                try {
                    om.setMailDate(sdf.parse(date));
                } catch (Exception e) {
                    //e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
                }

            }

            nodelist = nodeBodylist.extractAllNodesThatMatch(new HasAttributeFilter("class", "reply_content"), true);
            n = nodelist.toNodeArray();

            if (nodelist.size() > 0) {
                n = nodelist.toNodeArray();
                //System.out.println(n[0].toPlainTextString().trim());
                om.setMailDoc(n[0].toPlainTextString().trim());
            }


            List list = dao.listByHql("FROM OutMail WHERE userId = ? AND mailDate = ?", om.getUserId(), date);
            if (!(list != null && list.size() > 0)) {
                updateNewUserType(om.getUserId());

                Session session = dao.getHibernateTemplate().getSessionFactory().openSession();
                Transaction t = session.beginTransaction();
                t.begin();
                session.save(om);
                t.commit();
                session.close();


                System.out.println("保存邮件，用户ID ==" + om.getUserId());
            } else {
                continue;
            }


            List ul = dao.listByHql("FROM UserInfo WHERE u_id = ?", om.getUserId());
            if (ul.size() == 0) {
                UserInfo ui = new UserInfo();
                ui.setuId(om.getUserId());


                nodelist = nodeBodylist.extractAllNodesThatMatch(new HasAttributeFilter("onmousedown", "send_jy_pv2('msg_kx_nc');"), true);
                if (nodelist.size() > 0) {
                    n = nodelist.toNodeArray();
                    ui.setName(((LinkTag) n[0]).getLinkText());//name
                    ui.setUrl(((LinkTag) n[0]).getLink());//url
                }

                nodelist = nodeBodylist.extractAllNodesThatMatch(new HasAttributeFilter("class", "about"), true);
                if (nodelist.size() > 0) {
                    n = nodelist.extractAllNodesThatMatch(new TagNameFilter("p"), true).toNodeArray();
                    ui.setOther(n[0].toPlainTextString());//other
                }


                nodelist = nodeBodylist.extractAllNodesThatMatch(new HasAttributeFilter("onmousedown", "send_jy_pv2('msg_kx_zp');"), true);
                if (nodelist.size() > 0) {
                    n = nodelist.extractAllNodesThatMatch(new TagNameFilter("img"), true).toNodeArray();
                    ui.setImg(((ImageTag) n[0]).getImageURL());
                }

                ui.setType("2");
                ui.setCreateDate(new Date());


                Session session = dao.getHibernateTemplate().getSessionFactory().openSession();
                Transaction t = session.beginTransaction();
                t.begin();
                session.save(ui);
                t.commit();
                session.close();

            }


        }
    }


    private Set getInMailID() {
        Set set = new HashSet();
        hct.setUrl("http://www.jiayuan.com/msg/index.php?&p=1#toppage");
        hct.getInnerHTML();

        Parser p = Parser.createParser(hct.getInnerHTML(), "UTF-8");
        HtmlPage page = new HtmlPage(p);
        try {
            p.visitAllNodesWith(page);
        } catch (ParserException e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        }

        NodeList nodelist = page.getBody();

        NodeFilter nf = new HasAttributeFilter("style", "cursor:pointer;");
        nodelist = nodelist.extractAllNodesThatMatch(nf, true);


        Node[] n = nodelist.toNodeArray();
        for (Node node : n) {
            if (node instanceof LinkTag) {
                LinkTag l = (LinkTag) node;
                if (l.getAttribute("onclick") != null) {
                    set.add(l.getAttribute("onclick").replace("window.open('", "").replace("');", ""));
                }
            }
        }

        return set;
    }


    public void saveInMail() {

        Set<String> set = this.getInMailID();


        for (String url : set) {
            InMail om = new InMail();
            hct.setUrl("http://www.jiayuan.com" + url);

            om.setMailId(url.substring(url.indexOf("=") + 1, url.length() - 18));

            Parser p = Parser.createParser(hct.getInnerHTML(), "UTF-8");
            HtmlPage page = new HtmlPage(p);
            try {
                p.visitAllNodesWith(page);
            } catch (ParserException e) {
                e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
            }

            NodeList nodeBodylist = page.getBody();
            NodeList nodelist;
            Node[] n;


            nodelist = nodeBodylist.extractAllNodesThatMatch(new HasAttributeFilter("class", "recipient_status"), true);

            n = nodelist.toNodeArray();
            for (Node node : n) {
                nodelist = node.getChildren().extractAllNodesThatMatch(new TagNameFilter("a"), true);
                if (nodelist.size() > 0) {
                    LinkTag l = (LinkTag) nodelist.toNodeArray()[0];
                    System.out.println(l.getLink().replace("http://www.jiayuan.com/", "").replace("?lt=msgbox", ""));
                    om.setUserId(l.getLink().replace("http://www.jiayuan.com/", "").replace("?lt=msgbox", ""));
                }
            }

            if (om.getUserId() == null || om.getUserId().equals("")) {
                continue;
            }


            nodelist = nodeBodylist.extractAllNodesThatMatch(new AndFilter(new TagNameFilter("li"), new HasAttributeFilter("class", "time")), true);
            n = nodelist.toNodeArray();

            String date = "";
            if (nodelist.size() > 0) {
                n = nodelist.toNodeArray();
                System.out.println(n[0].toPlainTextString().replace("发信时间：", ""));

                date = n[0].toPlainTextString().replace("发信时间：", "");
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                try {
                    om.setMailDate(sdf.parse(date));
                } catch (Exception e) {
                    //e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
                }

            }


            nodelist = nodeBodylist.extractAllNodesThatMatch(new HasAttributeFilter("class", "reply_content"), true);
            n = nodelist.toNodeArray();

            if (nodelist.size() > 0) {
                n = nodelist.toNodeArray();
                //System.out.println(n[0].toPlainTextString().trim());
                om.setMailDoc(n[0].toPlainTextString().trim());
            }

            List list = dao.listByHql("FROM InMail WHERE userId = ? AND mailDate = ?", om.getUserId(), date);
            if (!(list != null && list.size() > 0)) {

                Session session = dao.getHibernateTemplate().getSessionFactory().openSession();
                Transaction t = session.beginTransaction();
                t.begin();
                session.save(om);
                t.commit();
                session.close();


                updateNewUserType(om.getUserId());

                System.out.println("保存邮件，用户ID ==" + om.getUserId());
            }


        }
    }


    private void saveNewUserList() {

        List<NameValuePair> list = new ArrayList<NameValuePair>();
        list.add(new BasicNameValuePair("max_age", "22"));
        list.add(new BasicNameValuePair("min_age", "0"));
//        list.add(new BasicNameValuePair("p", "5"));
        list.add(new BasicNameValuePair("sex", "f"));
        list.add(new BasicNameValuePair("work_location", "11"));
        list.add(new BasicNameValuePair("work_sublocation", "1100"));

        String html = hct.post("http://www.jiayuan.com/newmember/index.php", list);
        html = html.substring(html.indexOf("登录弹出结束 -->") + 10, html.length());
        html = "<html><body>" + html;

        Parser p = Parser.createParser(html, "UTF-8");
        HtmlPage page = new HtmlPage(p);
        try {
            p.visitAllNodesWith(page);
        } catch (ParserException e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        }

        NodeList nodeBodylist = page.getBody();
        NodeList nodelist;
        Node[] n;


        NodeFilter nfA = new TagNameFilter("a");
        NodeFilter nfIMG = new TagNameFilter("img");

        NodeFilter nf1 = new HasAttributeFilter("class", "dl101216");
        NodeFilter nf2 = new TagNameFilter("dl");
        NodeFilter nf3 = new AndFilter(nf1, nf2);


        nodelist = nodeBodylist.extractAllNodesThatMatch(nf3, true);
        n = nodelist.toNodeArray();
        for (Node node : n) {
            NewUser nu = new NewUser();

            //头像
            n = node.getChildren().extractAllNodesThatMatch(nfIMG, true).toNodeArray();
            nu.setImg(((ImageTag) n[0]).getImageURL());
            if (nu.getImg().indexOf("nopic_f") > -1) {
                nu.setImgType("2");
            } else {
                nu.setImgType("1");
            }

            nodelist = node.getChildren().extractAllNodesThatMatch(new HasAttributeFilter("class", "photo_content"), true);

            //用户名，ID,主页地址
            n = nodelist.extractAllNodesThatMatch(nfA, true).toNodeArray();
            if (n.length > 0 && n[0] instanceof LinkTag) {
                LinkTag i = (LinkTag) n[0];
                nu.setName(i.getLinkText());
                nu.setuId(i.getAttribute("dispuid"));
                nu.setUrl("http://www.jiayuan.com/" + i.getAttribute("dispuid"));
            }


            if (n.length > 1 && n[1] instanceof LinkTag) {
                LinkTag i = (LinkTag) n[1];
                nu.setMail(i.getLink().replace("/msg/send.php?src=newmember&uhash=", ""));
            }


            nu.setOther(((LinkTag) node.getChildren().extractAllNodesThatMatch(new HasAttributeFilter("class", "nl"), true).toNodeArray()[0]
                    .getChildren().extractAllNodesThatMatch(nfA).toNodeArray()[0]).getLinkText());

            nu.setOther(nu.getOther() + "," + nodelist.extractAllNodesThatMatch(new HasAttributeFilter("class", "name"), true).toNodeArray()[1].toHtml().replace("<div class=\"name\"><b>", "").replace("</b></div>", ""));


            nu.setCreateDate(new Date());

            if (dao.listByHql("FROM NewUser WHERE uId = ?", nu.getuId()).size() > 0) {
                //调用头像检查方法
                continue;
            }
            if (dao.getObject(UserInfoView.class, nu.getuId()) == null) {
                nu.setnType("1");
            } else {
                nu.setnType("2");
            }
            dao.saveObject(nu);
        }
    }

    private void updateNewUserType(String uid) {
        List list = dao.listByHql("FROM NewUser WHERE uId=? AND nType=1", uid);
        if (list.size() > 0) {
            NewUser nu = (NewUser) list.get(0);
            nu.setnType("2");
            dao.saveObject(nu);
        }
    }

    public static void main(String[] args) {
        System.out.println(new Date().toString().replace(" ", ""));
    }


}
